<template>
  <fieldset>
    <legend>{{ isLogin ? "内容界面" : "登入界面" }}</legend>
    <div class="content" v-if="isLogin">
      <h1>列表展示</h1>
      <button @click="isLogin = false">点击退出登入</button>
      <button @click="getlist">点击获取列表数据</button>
      <h2>
        <img :src="userInfo.headimgurl" width="50" />
        昵称:
        <a href="">{{ userInfo.nickname }}</a>
      </h2>
      <ul>
        <li v-for="item in lists" :key="item._id">
          <b>{{ item.name }}</b>
          <button v-has:read="permissionBtns">查看</button>
          <button v-has:edit="permissionBtns">修改</button>
          <button v-has:delete="permissionBtns">删除</button>
          <button v-has:add="permissionBtns">增加</button>
        </li>
      </ul>
    </div>
    <div class="login" v-else>
      <h1>请登入</h1>
      <label for="username">用户名:</label>
      <input type="text" id="username" v-model="username" />
      <br />
      <label for="password">密码:</label>
      <input type="text" v-model="password" @keydown.enter="login" />
      <br />
      <button @click="login">登入</button>
    </div>
  </fieldset>
</template>
<script>
const loginApi = (params = {}) => {
  return fetch("http://chst.vip/users/login", {
    method: "post",
    headers: {
      "content-type": "application/json",
    },
    body: JSON.stringify(params),
  })
    .then((body) => body.json())
    .catch((err) => err.toString());
};
const getlistApi = () => {
  return fetch("http://chst.vip/students/getstulist?count=8", {
    method: "get",
    headers: {
      authorization: sessionStorage.getItem("user-token"),
    },
  })
    .then((body) => body.json())
    .catch((err) => err.toString());
};
export default {
  data() {
    return {
      isLogin: false,
      username: "",
      password: "",
      userInfo: {},
      lists: [],
      permissionBtns: [],
    };
  },
  methods: {
    async login() {
      let res = await loginApi({
        username: this.username,
        password: this.password,
      });
      console.log(res);
      if (res.state) {
        this.isLogin = true;
        this.userInfo = res.userInfo;
        sessionStorage.setItem("user-token", res.token);
        this.permissionBtns = res.permission.buttons;
        // this.getlist()
      } else {
        alert(res.msg);
      }
    },
    async getlist() {
      let res = await getlistApi();
      if (res.state) {
        this.lists = res.data;
      } else {
        alert(res.msg);
      }
    },
  },
  directives: {
    has: {
      inserted(el, binding) {
        console.log(binding);
        let role = binding.arg;
        let userRole = binding.value;
        let hasRole = userRole.includes(role);
        if (!hasRole) {
          el.disabled = true;
          // el.parentNode.removeChild(el)
        }
      },
    },
  },
};
</script>
<style>
ul {
  padding: 0;
  margin: 0;
  list-style: none;
}

li {
  /* border: 1px solid deeppink; */
  margin: 10px;
  max-width: 500px;
}
</style>